<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <!-- 导入页面的基本样式 -->
    <link rel="stylesheet" href="./css/search.css" />
    <!-- 导入 jQuery -->
    <script src="./lib/jquery.js"></script>
    <!-- 导入模板引擎文件 -->
    <script src="./lib/template-web.js"></script>
  </head>
  <body>
    <div class="container">
      <!-- Logo -->
      <img src="./images/taobao_logo.png" alt="" class="logo" />

      <div class="box">
        <!-- tab 栏 -->
        <div class="tabs">
          <div class="tab-active">宝贝</div>
          <div>店铺</div>
        </div>
        <!-- 搜索区域（搜索框和搜索按钮） -->
        <div class="search-box">
          <input
            type="text"
            id="ipt"
            class="ipt"
            placeholder="请输入要搜索的内容"
          /><button class="btnSearch">搜索</button>
        </div>
        <!-- 搜索建议列表 -->
        <div id="suggest-list"></div>
      </div>
    </div>
    <!-- 定义模板引擎 -->
    <script type="text/html" id="tpl-suggestList">
      {{each result}}
      <div class="suggest-item">{{$value[0]}}</div>
      {{/each}}
    </script>

    <script>
      $(function () {
        // 1.定义防抖的变量
        let timer = null
        // 定义缓存空对象
        let obj = {}
        // 2.定义防抖函数
        function debounceSearch(keywords) {
          timer = setTimeout(function() {
            getSuggestList(keywords)
          },500)
        }
        $("#ipt").on("keyup", function () {
          // 先清空防抖 定时器
          clearTimeout(timer)
          let keywords = $(this).val().trim();
          if (keywords.length <= 0) {
            return $('#suggest-list').empty().hide()
          }

          if (obj[keywords]) return renderSuggestList(obj[keywords])
          // 调用防抖函数
          debounceSearch(keywords)
        });

        // 发起请求函数
        function getSuggestList(kw) {
          $.ajax({
            url: "https://suggest.taobao.com/sug?q=" + kw,
            dataType: "jsonp",
            success: (res) => {
              renderSuggestList(res)
            },
          });
        }
        // 渲染函数
        function renderSuggestList(res) {
          if (res.result.length <= 0) return $('#suggest-list').empty().hide()
          let htmltrs = template('tpl-suggestList',res)
          $('#suggest-list').html(htmltrs).show()
          let k = $('#ipt').val().trim()
          obj[k] = res
        }
      });
    </script>
  </body>
</html>
